package com.wise.service.portal.content.newrecommendproducts;

import com.wise.entities.content.Product;
import com.wise.framework.dao.SqlSelect;
import com.wise.framework.daomodel.DaoList;
import com.wise.framework.entitiesbasic.IdTimeEntity;
import com.wise.model.content.enums.ProductState;
import com.wise.summer.v1.portal.content.newrecommendproducts.ListNewRecommendProducts;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.summerframework.model.SummerService;
import org.summerframework.model.SummerServiceBean;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
@SummerService
public class ListNewRecommendProductsService implements SummerServiceBean<ListNewRecommendProducts> {

	@Override
	public void sum(ListNewRecommendProducts summer) {
		List<ListNewRecommendProducts.Result> newRecommendProductList = getNewRecommendProductList();
		summer.setSummerResult(newRecommendProductList);
	}

	/**
	 * 查询新品推荐产品
	 *
	 * @return
	 */
	private List<ListNewRecommendProducts.Result> getNewRecommendProductList() {
		SqlSelect sqlSelect = SqlSelect.selec("*")
				.fromClassName(Product.class)
				.eq(Product._categoryType, 0)
				.eqLang(Product._lang)
				.eq(Product._state, ProductState.UP.value())
				.eq(Product._newRecommend, true);

		List<Product> result = DaoList.s(Product.class, sqlSelect);

		// 临时储存更新时间
		result.forEach(temp -> {
			if (temp.getLastUpdateDate() == null){
				temp.setLastUpdateDate(temp.getCreationDate());
			}
		});

		// 按照修改时间排序
		List<Product> sorted = result.stream()
				.sorted(Comparator.comparing(IdTimeEntity::getLastUpdateDate).reversed())
				.collect(Collectors.toList());
		// 复制到输出类
		List<ListNewRecommendProducts.Result> resultList = new ArrayList<>();
		for (Product product : sorted) {
			ListNewRecommendProducts.Result tempResult = new ListNewRecommendProducts.Result();
			BeanUtils.copyProperties(product, tempResult);
			resultList.add(tempResult);
		}

		return resultList;
	}

}
